#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
污染类型管理服务
提供污染类型的CRUD操作、层级管理、样例管理等功能
"""

from typing import Dict, Any, List, Optional
from models.pollution_type import PollutionType, PollutionTypeLevel, PollutionTypeExample
from core.database import get_db_session
from core.logging_config import get_logger
from sqlalchemy.sql import func

logger = get_logger("pollution_type_service")


class PollutionTypeService:
    """污染类型管理服务"""
    
    def __init__(self):
        self.cache = {}  # 简单缓存
    
    def create_pollution_type(self, customer_id: str, type_data: Dict[str, Any]) -> PollutionType:
        """创建污染类型"""
        with get_db_session() as db:
            # 添加客户标识
            type_data["customer_id"] = customer_id

            # 验证数据（新的验证逻辑会自动修正层级）
            self._validate_type_data(customer_id, type_data, db_session=db)

            # 如果层级仍未设置，自动计算
            if "level" not in type_data:
                calculated_level = self._calculate_type_level(db, customer_id, type_data.get("parent_code"))
                type_data["level"] = calculated_level

            # 创建记录
            pollution_type = PollutionType(**type_data)
            db.add(pollution_type)
            db.commit()
            db.refresh(pollution_type)

            # 如果有父级，创建关系
            if pollution_type.parent_code:
                self._create_hierarchy_relation(db, customer_id, pollution_type)

            logger.info(f"客户 {customer_id} 创建污染类型: {pollution_type.name} (层级: {pollution_type.level})")
            # 返回字典数据而不是ORM对象，避免会话外访问问题
            return pollution_type.to_dict(db_session=db)
    
    def update_pollution_type(self, customer_id: str, type_id: int, update_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """更新污染类型"""
        with get_db_session() as db:
            pollution_type = db.query(PollutionType).filter(
                PollutionType.id == type_id,
                PollutionType.customer_id == customer_id
            ).first()
            if not pollution_type:
                return None

            # 验证更新数据（排除当前记录的ID检查）
            if "code" in update_data or "name" in update_data or "parent_code" in update_data:
                # 准备验证数据
                validation_data = {
                    "code": update_data.get("code", pollution_type.code),
                    "name": update_data.get("name", pollution_type.name),
                    "parent_code": update_data.get("parent_code", pollution_type.parent_code),
                    "level": update_data.get("level", pollution_type.level)
                }

                # 验证数据（新的验证逻辑会自动修正层级）
                self._validate_type_data(customer_id, validation_data, exclude_id=type_id, db_session=db)

                # 更新数据中可能被修正的层级
                update_data["level"] = validation_data["level"]
                if "parent_code" in validation_data:
                    update_data["parent_code"] = validation_data["parent_code"]

            # 更新字段
            for key, value in update_data.items():
                if hasattr(pollution_type, key):
                    setattr(pollution_type, key, value)

            pollution_type.updated_at = func.now()
            db.commit()
            db.refresh(pollution_type)

            logger.info(f"客户 {customer_id} 更新污染类型: {pollution_type.name}")

            # 在当前会话内转换为字典，避免会话外访问问题
            result = pollution_type.to_dict(db_session=db)
            return result
    
    def delete_pollution_type(self, customer_id: str, type_id: int) -> bool:
        """删除污染类型"""
        with get_db_session() as db:
            # 参数验证
            if not isinstance(type_id, int) or type_id <= 0:
                raise ValueError("无效的类型ID")

            pollution_type = db.query(PollutionType).filter(
                PollutionType.id == type_id,
                PollutionType.customer_id == customer_id
            ).first()
            if not pollution_type:
                return False

            # 检查是否有子级（相同客户）
            children_count = db.query(PollutionType).filter(
                PollutionType.customer_id == customer_id,
                PollutionType.parent_code == pollution_type.code,
                PollutionType.is_active == True
            ).count()

            if children_count > 0:
                raise ValueError(f"类型 {pollution_type.name} 包含子级，无法删除")

            # 软删除
            pollution_type.is_active = False
            pollution_type.updated_at = func.now()
            db.commit()

            logger.info(f"客户 {customer_id} 删除污染类型: {pollution_type.name}")
            return True
    
    def get_pollution_type(self, customer_id: str, type_id: int) -> Optional[Dict[str, Any]]:
        """获取单个污染类型"""
        with get_db_session() as db:
            pollution_type = db.query(PollutionType).filter(
                PollutionType.id == type_id,
                PollutionType.customer_id == customer_id,
                PollutionType.is_active == True
            ).first()

            if not pollution_type:
                return None

            # 在会话内转换为字典，避免会话外访问问题
            return pollution_type.to_dict(db_session=db)
    
    def get_pollution_type_by_code(self, customer_id: str, code: str) -> Optional[PollutionType]:
        """通过代码获取污染类型"""
        with get_db_session() as db:
            return db.query(PollutionType).filter(
                PollutionType.customer_id == customer_id,
                PollutionType.code == code,
                PollutionType.is_active == True
            ).first()

    def get_pollution_type_by_name(self, customer_id: str, name: str, db) -> Optional[PollutionType]:
        """通过名称获取污染类型"""
        # with get_db_session() as db:
        return db.query(PollutionType).filter(
            PollutionType.customer_id == customer_id,
            PollutionType.name == name,
            PollutionType.is_active == True
        ).first()
    
    def get_all_pollution_types(self, customer_id: str, active_only: bool = True, db=None) -> List[Dict[str, Any]]:
        """获取客户所有污染类型"""
        if db:
            query = db.query(PollutionType).filter(PollutionType.customer_id == customer_id)
            if active_only:
                query = query.filter(PollutionType.is_active == True)
            types = query.order_by(PollutionType.sort_order, PollutionType.code).all()

            # 在会话内转换为字典，避免延迟加载问题
            result = []
            for ptype in types:
                type_dict = {
                    "id": ptype.id,
                    "customer_id": ptype.customer_id,
                    "code": ptype.code,
                    "name": ptype.name,
                    "parent_code": ptype.parent_code,
                    "level": ptype.level,
                    "tag_name": ptype.tag_name,
                    "tag_category": ptype.tag_category,
                    "usage_scope": ptype.usage_scope,
                    "exclusion_scope": ptype.exclusion_scope,
                    "display_name": ptype.display_name,
                    "parent_tag_code": ptype.parent_tag_code,
                    "sort_order": ptype.sort_order,
                    "description": ptype.description,
                    "is_active": ptype.is_active,
                    "is_system": ptype.is_system,
                    "created_at": ptype.created_at.isoformat() if ptype.created_at else None,
                    "updated_at": ptype.updated_at.isoformat() if ptype.updated_at else None,
                }

                # 使用SQL查询而不是关系属性来获取样例数量
                try:
                    count = db.query(PollutionTypeExample).filter(
                        PollutionTypeExample.pollution_type_id == ptype.id
                    ).count()
                    type_dict["examples_count"] = count
                except:
                    type_dict["examples_count"] = 0

                result.append(type_dict)

            return result
        with get_db_session() as db:
            query = db.query(PollutionType).filter(PollutionType.customer_id == customer_id)
            if active_only:
                query = query.filter(PollutionType.is_active == True)
            types = query.order_by(PollutionType.sort_order, PollutionType.code).all()

            # 在会话内转换为字典，避免延迟加载问题
            result = []
            for ptype in types:
                type_dict = {
                    "id": ptype.id,
                    "customer_id": ptype.customer_id,
                    "code": ptype.code,
                    "name": ptype.name,
                    "parent_code": ptype.parent_code,
                    "level": ptype.level,
                    "tag_name": ptype.tag_name,
                    "tag_category": ptype.tag_category,
                    "usage_scope": ptype.usage_scope,
                    "exclusion_scope": ptype.exclusion_scope,
                    "display_name": ptype.display_name,
                    "parent_tag_code": ptype.parent_tag_code,
                    "sort_order": ptype.sort_order,
                    "description": ptype.description,
                    "is_active": ptype.is_active,
                    "is_system": ptype.is_system,
                    "created_at": ptype.created_at.isoformat() if ptype.created_at else None,
                    "updated_at": ptype.updated_at.isoformat() if ptype.updated_at else None,
                }

                # 使用SQL查询而不是关系属性来获取样例数量
                try:
                    count = db.query(PollutionTypeExample).filter(
                        PollutionTypeExample.pollution_type_id == ptype.id
                    ).count()
                    type_dict["examples_count"] = count
                except:
                    type_dict["examples_count"] = 0

                result.append(type_dict)

            return result
    
    def get_hierarchy_tree(self, customer_id: str) -> List[Dict[str, Any]]:
        """获取客户层级树结构"""
        with get_db_session() as db:
            # 获取客户所有激活的类型
            all_types = db.query(PollutionType).filter(
                PollutionType.customer_id == customer_id,
                PollutionType.is_active == True
            ).order_by(PollutionType.sort_order, PollutionType.code).all()
            
            # 构建树结构
            type_dict = {ptype.code: ptype for ptype in all_types}
            tree = []
            
            for ptype in all_types:
                if not ptype.parent_code:
                    # 一级分类
                    tree.append(self._build_tree_node(ptype, type_dict))
            
            return tree
    
    def _build_tree_node(self, ptype: PollutionType, type_dict: Dict[str, PollutionType]) -> Dict[str, Any]:
        """构建树节点"""
        node = {
            "id": ptype.id,
            "code": ptype.code,
            "name": ptype.name,
            "level": ptype.level,
            "description": ptype.description,
            "children": []
        }
        
        # 添加子节点
        for child in type_dict.values():
            if child.parent_code == ptype.code:
                node["children"].append(self._build_tree_node(child, type_dict))
        
        return node
    
    def search_pollution_types(self, customer_id: str, keyword: str) -> List[Dict[str, Any]]:
        """搜索客户污染类型"""
        with get_db_session() as db:
            types = db.query(PollutionType).filter(
                PollutionType.customer_id == customer_id,
                PollutionType.is_active == True,
                (
                    PollutionType.name.contains(keyword) |
                    PollutionType.code.contains(keyword) |
                    PollutionType.description.contains(keyword)
                )
            ).all()

            # 在会话内转换为字典，避免延迟加载问题
            result = []
            for ptype in types:
                type_dict = {
                    "id": ptype.id,
                    "customer_id": ptype.customer_id,
                    "code": ptype.code,
                    "name": ptype.name,
                    "parent_code": ptype.parent_code,
                    "level": ptype.level,
                    "tag_name": ptype.tag_name,
                    "tag_category": ptype.tag_category,
                    "usage_scope": ptype.usage_scope,
                    "exclusion_scope": ptype.exclusion_scope,
                    "display_name": ptype.display_name,
                    "parent_tag_code": ptype.parent_tag_code,
                    "sort_order": ptype.sort_order,
                    "description": ptype.description,
                    "is_active": ptype.is_active,
                    "is_system": ptype.is_system,
                    "created_at": ptype.created_at.isoformat() if ptype.created_at else None,
                    "updated_at": ptype.updated_at.isoformat() if ptype.updated_at else None,
                }

                # 使用SQL查询而不是关系属性来获取样例数量
                try:
                    count = db.query(PollutionTypeExample).filter(
                        PollutionTypeExample.pollution_type_id == ptype.id
                    ).count()
                    type_dict["examples_count"] = count
                except:
                    type_dict["examples_count"] = 0

                result.append(type_dict)

            return result
    
    def copy_types_to_customer(self, source_customer_id: str, target_customer_id: str) -> int:
        """复制污染类型到另一个客户"""
        with get_db_session() as db:
            # 获取源客户的所有类型
            source_types = db.query(PollutionType).filter(
                PollutionType.customer_id == source_customer_id,
                PollutionType.is_active == True
            ).all()
            
            # 创建目标客户的类型
            created_count = 0
            type_mapping = {}  # 源ID -> 目标ID
            
            # 先创建所有类型（不处理关系）
            for source_type in source_types:
                type_data = {
                    "customer_id": target_customer_id,
                    "code": source_type.code,
                    "name": source_type.name,
                    "parent_code": None,  # 暂时设为None
                    "level": source_type.level,
                    "tag_name": source_type.tag_name,
                    "tag_category": source_type.tag_category,
                    "usage_scope": source_type.usage_scope,
                    "exclusion_scope": source_type.exclusion_scope,
                    "display_name": source_type.display_name,
                    "parent_tag_code": source_type.parent_tag_code,
                    "sort_order": source_type.sort_order,
                    "description": source_type.description,
                    "is_active": True,
                    "is_system": False
                }
                
                new_type = PollutionType(**type_data)
                db.add(new_type)
                db.flush()  # 获取ID
                type_mapping[source_type.id] = new_type.id
                created_count += 1
            
            # 更新父子关系
            for source_type in source_types:
                if source_type.parent_code:
                    # 找到目标类型并更新parent_code
                    target_type = db.query(PollutionType).filter(
                        PollutionType.id == type_mapping[source_type.id]
                    ).first()
                    if target_type:
                        target_type.parent_code = source_type.parent_code
            
            db.commit()
            logger.info(f"从客户 {source_customer_id} 复制 {created_count} 个类型到客户 {target_customer_id}")
            return created_count
    
    def _create_hierarchy_relation(self, db, customer_id: str, pollution_type: PollutionType):
        """创建层级关系（已弃用，层级关系通过parent_code字段维护）"""
        # 层级关系现在通过 parent_code 字段直接维护，不需要单独的关系表
        # 这个方法保留是为了兼容性，但实际不再创建关系记录
        logger.info(f"污染类型 {pollution_type.name} 的层级关系通过 parent_code 字段维护")
        pass
    
    def _calculate_type_level(self, db, customer_id: str, parent_code: str) -> int:
        """根据父级代码计算层级"""
        if not parent_code or parent_code == "" or parent_code == "nan":
            return 1  # 一级分类

        # 查询父级类型
        parent_type = db.query(PollutionType).filter(
            PollutionType.customer_id == customer_id,
            PollutionType.code == parent_code,
            PollutionType.is_active == True
        ).first()

        if not parent_type:
            logger.warning(f"未找到父级类型: {parent_code}")
            return 1

        # 递归计算层级
        return parent_type.level + 1

    def _validate_type_data(self, customer_id: str, type_data: Dict[str, Any], exclude_id: Optional[int] = None, db_session=None):
        """验证类型数据"""
        required_fields = ["code", "name"]
        for field in required_fields:
            if field not in type_data or not type_data[field]:
                raise ValueError(f"字段 {field} 不能为空")

        # 检查代码重复（同一客户内，排除当前编辑的记录）
        code = type_data["code"]

        # 如果传入了数据库会话，直接使用；否则创建新会话
        if db_session is not None:
            db = db_session
            existing = db.query(PollutionType).filter(
                PollutionType.customer_id == customer_id,
                PollutionType.code == code
            )
            # 如果是更新操作，排除当前记录
            if exclude_id:
                existing = existing.filter(PollutionType.id != exclude_id)
            existing = existing.first()
        else:
            with get_db_session() as db:
                existing = db.query(PollutionType).filter(
                    PollutionType.customer_id == customer_id,
                    PollutionType.code == code
                )
                # 如果是更新操作，排除当前记录
                if exclude_id:
                    existing = existing.filter(PollutionType.id != exclude_id)
                existing = existing.first()

        if existing:
            raise ValueError(f"客户 {customer_id} 中代码 {code} 已存在")

        # 自动修正层级与父级关系的一致性，而不是抛出错误
        parent_code = type_data.get("parent_code")
        level = type_data.get("level", 1)

        # 清理 parent_code 值
        if parent_code in [None, "", "nan", "null", "undefined"]:
            parent_code = None
            type_data["parent_code"] = None

        if parent_code:
            # 如果有父级，自动计算层级
            if level == 1:
                # 自动修正层级
                calculated_level = self._calculate_type_level_with_db(customer_id, parent_code, db_session=db_session)
                type_data["level"] = calculated_level
                logger.info(f"自动修正层级: 代码 {code} 从层级 1 调整为层级 {calculated_level}")
        else:
            # 如果没有父级，确保层级为1
            if level > 1:
                type_data["level"] = 1
                logger.info(f"自动修正层级: 代码 {code} 从层级 {level} 调整为层级 1")

        # 检查层级范围
        if type_data["level"] < 1 or type_data["level"] > 3:
            raise ValueError("层级必须是1、2或3")

    def _calculate_type_level_with_db(self, customer_id: str, parent_code: str, db_session=None) -> int:
        """使用数据库会话计算层级"""
        if db_session is not None:
            return self._calculate_type_level(db_session, customer_id, parent_code)
        else:
            with get_db_session() as db:
                return self._calculate_type_level(db, customer_id, parent_code)
    
    # 样例管理方法
    def create_pollution_type_example(self, customer_id: str, pollution_type_id: int, example_data: Dict[str, Any]) -> PollutionTypeExample:
        """创建污染类型样例"""
        with get_db_session() as db:
            # 验证污染类型存在且属于该客户
            pollution_type = db.query(PollutionType).filter(
                PollutionType.id == pollution_type_id,
                PollutionType.customer_id == customer_id
            ).first()
            if not pollution_type:
                raise ValueError(f"污染类型ID {pollution_type_id} 不存在或不属于客户 {customer_id}")
            
            # 添加客户标识
            example_data["customer_id"] = customer_id
            example_data["pollution_type_id"] = pollution_type_id
            
            # 验证数据
            if "example_content" not in example_data or not example_data["example_content"]:
                raise ValueError("样例内容不能为空")
            
            # 创建记录
            example = PollutionTypeExample(**example_data)
            db.add(example)
            db.commit()
            db.refresh(example)
            
            logger.info(f"客户 {customer_id} 创建污染类型样例: {pollution_type.name}")
            # 返回字典数据而不是ORM对象，避免会话外访问问题
            return example.to_dict()
    
    def update_pollution_type_example(self, customer_id: str, example_id: int, update_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """更新污染类型样例"""
        with get_db_session() as db:
            example = db.query(PollutionTypeExample).filter(
                PollutionTypeExample.id == example_id,
                PollutionTypeExample.customer_id == customer_id
            ).first()
            if not example:
                return None

            # 更新字段
            for key, value in update_data.items():
                if hasattr(example, key):
                    setattr(example, key, value)

            example.updated_at = func.now()
            db.commit()
            db.refresh(example)

            logger.info(f"客户 {customer_id} 更新污染类型样例: {example_id}")
            # 返回字典数据而不是ORM对象，避免会话外访问问题
            return example.to_dict()
    
    def delete_pollution_type_example(self, customer_id: str, example_id: int) -> bool:
        """删除污染类型样例"""
        with get_db_session() as db:
            example = db.query(PollutionTypeExample).filter(
                PollutionTypeExample.id == example_id,
                PollutionTypeExample.customer_id == customer_id
            ).first()
            if not example:
                return False
            
            # 软删除
            example.is_active = False
            example.updated_at = func.now()
            db.commit()
            
            logger.info(f"客户 {customer_id} 删除污染类型样例: {example_id}")
            return True
    
    def get_pollution_type_examples(self, customer_id: str, pollution_type_id: Optional[int] = None, active_only: bool = True, db=None) -> List[Dict[str, Any]]:
        """获取污染类型样例列表"""
        if db:
            query = db.query(PollutionTypeExample).filter(
                PollutionTypeExample.customer_id == customer_id
            )

            if pollution_type_id:
                query = query.filter(PollutionTypeExample.pollution_type_id == pollution_type_id)

            if active_only:
                query = query.filter(PollutionTypeExample.is_active == True)

            examples = query.order_by(PollutionTypeExample.created_at.desc()).all()
            # 在会话内转换为字典，避免延迟加载问题
            return [example.to_dict() for example in examples]
        with get_db_session() as db:
            query = db.query(PollutionTypeExample).filter(
                PollutionTypeExample.customer_id == customer_id
            )

            if pollution_type_id:
                query = query.filter(PollutionTypeExample.pollution_type_id == pollution_type_id)

            if active_only:
                query = query.filter(PollutionTypeExample.is_active == True)

            examples = query.order_by(PollutionTypeExample.created_at.desc()).all()
            # 在会话内转换为字典，避免延迟加载问题
            return [example.to_dict() for example in examples]
    
    def search_examples_by_keywords(self, customer_id: str, keywords: List[str]) -> List[Dict[str, Any]]:
        """根据关键词搜索样例"""
        with get_db_session() as db:
            results = []
            examples = db.query(PollutionTypeExample).filter(
                PollutionTypeExample.customer_id == customer_id,
                PollutionTypeExample.is_active == True
            ).all()
            
            for example in examples:
                example_keywords = example.get_keywords_list()
                # 检查是否有匹配的关键词
                matched_keywords = []
                for keyword in keywords:
                    for example_keyword in example_keywords:
                        if keyword.lower() in example_keyword.lower():
                            matched_keywords.append(keyword)
                            break
                
                if matched_keywords:
                    results.append({
                        "example": example.to_dict(),
                        "matched_keywords": matched_keywords,
                        "match_count": len(matched_keywords)
                    })
            
            # 按匹配数量排序
            results.sort(key=lambda x: x["match_count"], reverse=True)
            return results
    
    def analyze_content_with_examples(self, customer_id: str, content: str) -> List[Dict[str, Any]]:
        """使用样例分析内容"""
        with get_db_session() as db:
            # 获取所有激活的样例
            examples = db.query(PollutionTypeExample).filter(
                PollutionTypeExample.customer_id == customer_id,
                PollutionTypeExample.is_active == True
            ).all()
            
            analysis_results = []
            
            for example in examples:
                # 关键词匹配
                keywords = example.get_keywords_list()
                matched_keywords = []
                match_score = 0
                
                for keyword in keywords:
                    if keyword.lower() in content.lower():
                        matched_keywords.append(keyword)
                        match_score += 1
                
                if matched_keywords:
                    # 计算置信度
                    keyword_match_ratio = match_score / len(keywords) if keywords else 0
                    final_confidence = min(example.confidence_level * keyword_match_ratio, 1.0)
                    
                    analysis_results.append({
                        "pollution_type_id": example.pollution_type_id,
                        "pollution_type_name": example.pollution_type.name if example.pollution_type else None,
                        "example_id": example.id,
                        "matched_keywords": matched_keywords,
                        "match_score": match_score,
                        "confidence": final_confidence,
                        "judgment_basis": example.judgment_basis,
                        "similar_example": example.example_content[:200] + "..." if len(example.example_content) > 200 else example.example_content
                    })
            
            # 按置信度排序
            analysis_results.sort(key=lambda x: x["confidence"], reverse=True)
            return analysis_results

    def batch_delete_pollution_types(self, customer_id: str, type_ids: List[int]) -> Dict[str, Any]:
        """批量删除污染类型"""
        with get_db_session() as db:
            deleted_count = 0
            failed_count = 0
            failed_items = []

            for type_id in type_ids:
                try:
                    # 检查是否存在
                    pollution_type = db.query(PollutionType).filter(
                        PollutionType.id == type_id,
                        PollutionType.customer_id == customer_id,
                        PollutionType.is_deleted == False
                    ).first()

                    if not pollution_type:
                        failed_count += 1
                        failed_items.append({
                            "id": type_id,
                            "error": "污染类型不存在"
                        })
                        continue

                    # 检查是否有子类型
                    has_children = db.query(PollutionType).filter(
                        PollutionType.parent_code == pollution_type.code,
                        PollutionType.customer_id == customer_id,
                        PollutionType.is_deleted == False
                    ).first()

                    if has_children:
                        failed_count += 1
                        failed_items.append({
                            "id": type_id,
                            "code": pollution_type.code,
                            "error": "存在子类型，无法删除"
                        })
                        continue

                    # 软删除
                    pollution_type.is_deleted = True
                    deleted_count += 1

                except Exception as e:
                    failed_count += 1
                    failed_items.append({
                        "id": type_id,
                        "error": str(e)
                    })
                    logger.error(f"删除污染类型 {type_id} 失败: {str(e)}")

            db.commit()

            logger.info(f"批量删除污染类型完成 (客户: {customer_id}, 成功: {deleted_count}, 失败: {failed_count})")

            return {
                "deleted_count": deleted_count,
                "failed_count": failed_count,
                "failed_items": failed_items
            }

    def batch_toggle_pollution_types(self, customer_id: str, type_ids: List[int], is_active: bool) -> Dict[str, Any]:
        """批量激活/停用污染类型"""
        with get_db_session() as db:
            updated_count = 0
            failed_count = 0
            failed_items = []

            for type_id in type_ids:
                try:
                    # 检查是否存在
                    pollution_type = db.query(PollutionType).filter(
                        PollutionType.id == type_id,
                        PollutionType.customer_id == customer_id,
                        PollutionType.is_deleted == False
                    ).first()

                    if not pollution_type:
                        failed_count += 1
                        failed_items.append({
                            "id": type_id,
                            "error": "污染类型不存在"
                        })
                        continue

                    # 更新状态
                    pollution_type.is_active = is_active
                    updated_count += 1

                except Exception as e:
                    failed_count += 1
                    failed_items.append({
                        "id": type_id,
                        "error": str(e)
                    })
                    logger.error(f"更新污染类型 {type_id} 状态失败: {str(e)}")

            db.commit()

            action = "激活" if is_active else "停用"
            logger.info(f"批量{action}污染类型完成 (客户: {customer_id}, 成功: {updated_count}, 失败: {failed_count})")

            return {
                "updated_count": updated_count,
                "failed_count": failed_count,
                "failed_items": failed_items
            }


# 全局服务实例
pollution_type_service = PollutionTypeService()